<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License Guard - 远程授权管理中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .server-status {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 20px;
            background: #f0f0f0;
            border-radius: 20px;
        }

        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #28a745;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(40, 167, 69, 0); }
            100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
        }

        .container {
            max-width: 1400px;
            margin: 20px auto;
            padding: 0 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        .stat-value {
            font-size: 32px;
            font-weight: bold;
            color: #333;
            margin: 10px 0;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
        }

        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            background: white;
            padding: 10px;
            border-radius: 10px;
        }

        .tab {
            padding: 10px 20px;
            background: #f0f0f0;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .tab-content {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        input, select, textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 14px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-revoked {
            background: #f8d7da;
            color: #721c24;
        }

        .status-expired {
            background: #fff3cd;
            color: #856404;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
        }

        .btn-danger {
            background: #dc3545;
        }

        .btn-info {
            background: #17a2b8;
        }

        .result-box {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed #dee2e6;
            display: none;
        }

        .result-box.show {
            display: block;
        }

        .license-key-display {
            font-family: 'Courier New', monospace;
            font-size: 14px;
            background: white;
            padding: 15px;
            border-radius: 5px;
            word-break: break-all;
            margin: 10px 0;
            border: 1px solid #dee2e6;
        }

        .server-config {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .config-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .config-label {
            font-weight: 600;
            color: #555;
            min-width: 100px;
        }

        .config-value {
            flex: 1;
            padding: 8px;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }

        .client-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
        }

        .client-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }

        .info-item {
            font-size: 14px;
        }

        .info-label {
            font-weight: 600;
            color: #666;
        }

        .online-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .online {
            background: #28a745;
        }

        .offline {
            background: #dc3545;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <div class="logo">
                🔐 License Guard 远程管理中心
                <span style="font-size: 14px; margin-left: 10px; opacity: 0.7;">by Chaxi</span>
            </div>
            <div class="server-status">
                <span class="status-indicator"></span>
                <span>服务器运行中</span>
                <span id="serverUrl">http://localhost:3000</span>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- 统计卡片 -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">总授权数</div>
                <div class="stat-value" id="totalLicenses">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">活跃授权</div>
                <div class="stat-value" id="activeLicenses">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">在线客户端</div>
                <div class="stat-value" id="onlineClients">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">已撤销授权</div>
                <div class="stat-value" id="revokedLicenses">0</div>
            </div>
        </div>

        <!-- 标签页 -->
        <div class="tabs">
            <button class="tab active" onclick="switchTab('generate')">生成授权</button>
            <button class="tab" onclick="switchTab('licenses')">授权管理</button>
            <button class="tab" onclick="switchTab('clients')">客户端监控</button>
            <button class="tab" onclick="switchTab('settings')">服务器设置</button>
        </div>

        <!-- 生成授权 -->
        <div id="generate-tab" class="tab-content">
            <h2>生成新授权</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="customerName">客户名称</label>
                    <input type="text" id="customerName" placeholder="输入客户名称">
                </div>
                <div class="form-group">
                    <label for="machineId">机器标识 *</label>
                    <input type="text" id="machineId" placeholder="输入目标机器ID" required>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="licenseType">授权类型</label>
                    <select id="licenseType" onchange="handleTypeChange()">
                        <option value="trial">试用版 (30天)</option>
                        <option value="standard" selected>标准版 (365天)</option>
                        <option value="enterprise">企业版 (永久)</option>
                        <option value="custom">自定义</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="duration">自定义时长</label>
                    <input type="number" id="duration" placeholder="仅自定义类型" disabled>
                </div>
            </div>

            <div class="form-row" id="customTimeRow" style="display: none;">
                <div class="form-group">
                    <label for="timeUnit">时间单位</label>
                    <select id="timeUnit">
                        <option value="days">天</option>
                        <option value="weeks">周</option>
                        <option value="months">月</option>
                        <option value="years">年</option>
                    </select>
                </div>
                <div class="form-group">
                    <!-- 占位 -->
                </div>
            </div>

            <div class="form-group">
                <label for="features">功能权限</label>
                <select id="features" multiple style="height: 100px;">
                    <option value="basic" selected>基础功能</option>
                    <option value="advanced">高级功能</option>
                    <option value="premium">专业功能</option>
                    <option value="all">所有功能</option>
                </select>
                <small style="color: #666;">按住 Ctrl 可多选</small>
            </div>

            <button onclick="generateLicense()">🚀 生成授权码</button>

            <div id="resultBox" class="result-box">
                <h3>✅ 授权生成成功！</h3>
                <div class="license-key-display" id="licenseKey"></div>
                <div style="margin-top: 15px;">
                    <button onclick="copyLicense()">📋 复制授权码</button>
                    <button onclick="downloadLicense()" style="margin-left: 10px;">💾 下载文件</button>
                </div>
            </div>
        </div>

        <!-- 授权管理 -->
        <div id="licenses-tab" class="tab-content" style="display: none;">
            <h2>授权列表</h2>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>授权ID</th>
                            <th>客户名称</th>
                            <th>类型</th>
                            <th>状态</th>
                            <th>生成时间</th>
                            <th>过期时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="licensesTable">
                        <!-- 动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 客户端监控 -->
        <div id="clients-tab" class="tab-content" style="display: none;">
            <h2>连接的客户端</h2>
            <div id="clientsList">
                <!-- 动态生成 -->
            </div>
            
            <div style="margin-top: 20px;">
                <h3>远程操作</h3>
                <div style="margin-top: 10px;">
                    <div class="form-group">
                        <label for="remoteMachineId">客户端机器ID</label>
                        <input type="text" id="remoteMachineId" placeholder="输入目标机器ID">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="revokeReason">撤销原因</label>
                            <input type="text" id="revokeReason" placeholder="例如：违反使用条款">
                        </div>
                        <div class="form-group" style="display: flex; align-items: flex-end;">
                            <button onclick="remoteRevokeLicense()" class="btn-danger" style="width: 100%;">远程撤销授权</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 服务器设置 -->
        <div id="settings-tab" class="tab-content" style="display: none;">
            <h2>服务器配置</h2>
            <div class="server-config">
                <div class="config-item">
                    <span class="config-label">服务器地址:</span>
                    <input type="text" class="config-value" id="serverAddress" value="http://localhost:3000">
                </div>
                <div class="config-item">
                    <span class="config-label">WebSocket:</span>
                    <input type="text" class="config-value" id="wsAddress" value="ws://localhost:3000">
                </div>
                <div class="config-item">
                    <span class="config-label">公钥:</span>
                    <textarea class="config-value" id="publicKey" rows="5" readonly></textarea>
                </div>
            </div>
            <button onclick="saveSettings()">💾 保存设置</button>
            <button onclick="testConnection()" style="margin-left: 10px;">🔍 测试连接</button>
        </div>
    </div>

    <script>
        let currentLicense = null;
        let ws = null;
        const SERVER_URL = window.location.origin;

        // 初始化
        window.onload = function() {
            loadStats();
            loadPublicKey();
            connectWebSocket();
            setInterval(loadStats, 5000); // 每5秒更新统计
        };

        // 加载统计信息
        async function loadStats() {
            try {
                const response = await fetch(`${SERVER_URL}/api/stats`);
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('totalLicenses').textContent = data.data.totalLicenses;
                    document.getElementById('activeLicenses').textContent = data.data.activeLicenses;
                    document.getElementById('onlineClients').textContent = data.data.onlineClients;
                    document.getElementById('revokedLicenses').textContent = data.data.revokedLicenses;
                }
            } catch (error) {
                console.error('加载统计失败:', error);
            }
        }

        // 加载公钥
        async function loadPublicKey() {
            try {
                const response = await fetch(`${SERVER_URL}/api/public-key`);
                const data = await response.json();
                document.getElementById('publicKey').value = data.publicKey;
            } catch (error) {
                console.error('加载公钥失败:', error);
            }
        }

        // WebSocket连接
        function connectWebSocket() {
            const wsUrl = `ws://${window.location.host}`;
            ws = new WebSocket(wsUrl);
            
            ws.onopen = () => {
                console.log('WebSocket连接成功');
            };
            
            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (data.type === 'clientList') {
                    updateClientsList(data.data);
                }
            };
            
            ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
            };
            
            ws.onclose = () => {
                console.log('WebSocket连接关闭，5秒后重连...');
                setTimeout(connectWebSocket, 5000);
            };
        }

        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.style.display = 'none';
            });
            
            // 移除所有标签的active类
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签内容
            document.getElementById(`${tabName}-tab`).style.display = 'block';
            
            // 添加active类到选中的标签
            event.target.classList.add('active');
            
            // 加载对应的数据
            if (tabName === 'licenses') {
                loadLicenses();
            } else if (tabName === 'clients') {
                loadClients();
            }
        }

        // 处理授权类型变化
        function handleTypeChange() {
            const type = document.getElementById('licenseType').value;
            const durationInput = document.getElementById('duration');
            const customTimeRow = document.getElementById('customTimeRow');
            
            if (type === 'custom') {
                durationInput.disabled = false;
                durationInput.value = 30;
                customTimeRow.style.display = 'grid';
            } else {
                durationInput.disabled = true;
                durationInput.value = '';
                customTimeRow.style.display = 'none';
            }
        }

        // 生成授权
        async function generateLicense() {
            const customerName = document.getElementById('customerName').value;
            const machineId = document.getElementById('machineId').value;
            const licenseType = document.getElementById('licenseType').value;
            const duration = document.getElementById('duration').value;
            const timeUnit = document.getElementById('timeUnit').value;
            const featuresSelect = document.getElementById('features');
            
            if (!machineId) {
                alert('请输入机器标识！');
                return;
            }
            
            const features = Array.from(featuresSelect.selectedOptions).map(option => option.value);
            
            const requestData = {
                type: licenseType,
                machineId: machineId,
                customerName: customerName,
                features: features
            };
            
            if (licenseType === 'custom' && duration) {
                requestData.duration = parseInt(duration);
                requestData.unit = timeUnit;
            }
            
            try {
                const response = await fetch(`${SERVER_URL}/api/generate-license`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentLicense = data.data;
                    document.getElementById('licenseKey').textContent = data.data.formattedKey;
                    document.getElementById('resultBox').classList.add('show');
                } else {
                    alert('生成失败: ' + data.error);
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            }
        }

        // 复制授权码
        function copyLicense() {
            if (!currentLicense) return;
            
            navigator.clipboard.writeText(currentLicense.licenseKey).then(() => {
                alert('授权码已复制到剪贴板！');
            });
        }

        // 下载授权文件
        function downloadLicense() {
            if (!currentLicense) return;
            
            const content = `License Guard 授权信息
====================================
授权ID: ${currentLicense.licenseInfo.id}
类型: ${currentLicense.licenseInfo.type}
客户: ${currentLicense.licenseInfo.customerName || '未指定'}
机器ID: ${currentLicense.licenseInfo.machineId}
生成时间: ${new Date(currentLicense.licenseInfo.issueDate).toLocaleString()}
过期时间: ${new Date(currentLicense.licenseInfo.expiryDate).toLocaleString()}
====================================

授权码:
${currentLicense.licenseKey}

====================================
请妥善保管此授权码！`;
            
            const blob = new Blob([content], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `license_${currentLicense.licenseInfo.id}.txt`;
            a.click();
            URL.revokeObjectURL(url);
        }

        // 加载授权列表
        async function loadLicenses() {
            try {
                const response = await fetch(`${SERVER_URL}/api/licenses`);
                const data = await response.json();
                
                if (data.success) {
                    const tbody = document.getElementById('licensesTable');
                    tbody.innerHTML = '';
                    
                    data.data.forEach(license => {
                        const row = document.createElement('tr');
                        const statusClass = license.status === 'active' ? 'status-active' : 
                                           license.status === 'revoked' ? 'status-revoked' : 'status-expired';
                        
                        row.innerHTML = `
                            <td>${license.id}</td>
                            <td>${license.customerName || '未指定'}</td>
                            <td>${license.type}</td>
                            <td><span class="status-badge ${statusClass}">${license.status}</span></td>
                            <td>${new Date(license.issueDate).toLocaleDateString()}</td>
                            <td>${new Date(license.expiryDate).toLocaleDateString()}</td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn-small btn-info" onclick="viewLicense('${license.id}')">查看</button>
                                    ${license.status === 'active' ? 
                                      `<button class="btn-small btn-danger" onclick="revokeLicense('${license.id}')">撤销</button>` : ''}
                                </div>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                }
            } catch (error) {
                console.error('加载授权列表失败:', error);
            }
        }

        // 加载客户端列表
        async function loadClients() {
            try {
                const response = await fetch(`${SERVER_URL}/api/clients`);
                const data = await response.json();
                
                if (data.success) {
                    const container = document.getElementById('clientsList');
                    container.innerHTML = '';
                    
                    data.data.forEach(client => {
                        const isOnline = client.status === 'online';
                        const card = document.createElement('div');
                        card.className = 'client-card';
                        
                        card.innerHTML = `
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <span class="online-indicator ${isOnline ? 'online' : 'offline'}"></span>
                                    <strong>机器ID:</strong> ${client.machineId}
                                </div>
                                <button onclick="viewClientDetails('${client.machineId}')" class="btn-small btn-info" style="margin: 0;">查看详情</button>
                            </div>
                            <div class="client-info">
                                <div class="info-item">
                                    <span class="info-label">状态:</span> ${isOnline ? '在线' : '离线'}
                                </div>
                                <div class="info-item">
                                    <span class="info-label">授权ID:</span> ${client.licenseInfo?.id || '未知'}
                                </div>
                                <div class="info-item">
                                    <span class="info-label">最后活跃:</span> ${new Date(client.lastSeen).toLocaleString()}
                                </div>
                                <div class="info-item">
                                    <span class="info-label">首次连接:</span> ${new Date(client.firstSeen).toLocaleString()}
                                </div>
                            </div>
                        `;
                        container.appendChild(card);
                    });
                }
            } catch (error) {
                console.error('加载客户端列表失败:', error);
            }
        }

        // 更新客户端列表（WebSocket）
        function updateClientsList(clients) {
            // 更新在线客户端数量
            document.getElementById('onlineClients').textContent = clients.length;
        }

        // 撤销授权
        async function revokeLicense(licenseId) {
            if (!confirm('确定要撤销此授权吗？')) return;
            
            const reason = prompt('请输入撤销原因:');
            
            try {
                const response = await fetch(`${SERVER_URL}/api/revoke-license`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ licenseId, reason })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('授权已撤销');
                    loadLicenses();
                    loadStats();
                } else {
                    alert('撤销失败: ' + data.error);
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            }
        }

        // 查看授权详情
        async function viewLicense(licenseId) {
            try {
                // 获取授权详情
                const response = await fetch(`${SERVER_URL}/api/license/${licenseId}`);
                const data = await response.json();
                
                if (!data.success) {
                    alert('获取授权详情失败: ' + data.error);
                    return;
                }
                
                // 创建弹窗显示详细信息
                const license = data.data;
                
                // 创建模态框
                const modal = document.createElement('div');
                modal.style.position = 'fixed';
                modal.style.top = '0';
                modal.style.left = '0';
                modal.style.width = '100%';
                modal.style.height = '100%';
                modal.style.background = 'rgba(0,0,0,0.7)';
                modal.style.display = 'flex';
                modal.style.justifyContent = 'center';
                modal.style.alignItems = 'center';
                modal.style.zIndex = '1000';
                
                // 模态框内容
                const modalContent = document.createElement('div');
                modalContent.style.background = 'white';
                modalContent.style.borderRadius = '10px';
                modalContent.style.padding = '30px';
                modalContent.style.width = '80%';
                modalContent.style.maxWidth = '800px';
                modalContent.style.maxHeight = '80vh';
                modalContent.style.overflowY = 'auto';
                
                // 格式化日期
                const formatDate = (dateString) => {
                    if (!dateString) return '未知';
                    try {
                        return new Date(dateString).toLocaleString();
                    } catch (e) {
                        return dateString;
                    }
                };
                
                // 标题和关闭按钮
                modalContent.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h2 style="margin: 0;">授权详情: ${license.id}</h2>
                        <button id="closeModal" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div>
                            <h3>基本信息</h3>
                            <table style="width: 100%; border-collapse: collapse;">
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">授权ID</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.id}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">类型</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.type}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">客户名称</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.customerName || '未指定'}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">状态</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">
                                        <span class="status-badge ${license.status === 'active' ? 'status-active' : 
                                                                  license.status === 'revoked' ? 'status-revoked' : 'status-expired'}">
                                            ${license.status}
                                        </span>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">机器ID</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.machineId}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">功能权限</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.features ? license.features.join(', ') : '基础功能'}</td>
                                </tr>
                            </table>
                        </div>
                        <div>
                            <h3>时间信息</h3>
                            <table style="width: 100%; border-collapse: collapse;">
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">生成时间</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${formatDate(license.issueDate)}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">过期时间</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${formatDate(license.expiryDate)}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">持续时间</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.duration} ${license.unit}</td>
                                </tr>
                                ${license.status === 'revoked' ? `
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">撤销时间</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${formatDate(license.revokedAt)}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">撤销原因</td>
                                    <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.revokeReason || '未指定'}</td>
                                </tr>
                                ` : ''}
                            </table>
                        </div>
                    </div>
                    ${license.status === 'active' ? `
                    <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
                        <button onclick="revokeLicense('${license.id}')" class="btn-danger" style="padding: 10px 20px;">撤销此授权</button>
                    </div>
                    ` : ''}
                `;
                
                modal.appendChild(modalContent);
                document.body.appendChild(modal);
                
                // 关闭模态框
                document.getElementById('closeModal').addEventListener('click', () => {
                    document.body.removeChild(modal);
                });
                
                // 点击模态框外部关闭
                modal.addEventListener('click', (event) => {
                    if (event.target === modal) {
                        document.body.removeChild(modal);
                    }
                });
                
            } catch (error) {
                console.error('获取授权详情失败:', error);
                alert('获取授权详情失败: ' + error.message);
            }
        }

        // 保存设置
        function saveSettings() {
            alert('设置已保存！');
        }

        // 测试连接
        async function testConnection() {
            try {
                const response = await fetch(`${SERVER_URL}/api/stats`);
                if (response.ok) {
                    alert('服务器连接正常！');
                } else {
                    alert('服务器连接失败！');
                }
            } catch (error) {
                alert('无法连接到服务器: ' + error.message);
            }
        }
        
        // 远程撤销授权
        async function remoteRevokeLicense() {
            const machineId = document.getElementById('remoteMachineId').value.trim();
            const reason = document.getElementById('revokeReason').value.trim();
            
            if (!machineId) {
                alert('请输入要撤销授权的客户端机器ID');
                return;
            }
            
            if (!confirm(`确定要远程撤销客户端 ${machineId} 的授权吗？此操作不可逆！`)) {
                return;
            }
            
            try {
                const response = await fetch(`${SERVER_URL}/api/remote-revoke`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        machineId: machineId,
                        reason: reason || '管理员操作'
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert(`已向客户端 ${machineId} 发送撤销指令`);
                    // 刷新客户端列表
                    loadClients();
                } else {
                    alert('撤销操作失败: ' + data.error);
                }
            } catch (error) {
                alert('请求失败: ' + error.message);
            }
        }
        
        // 查看客户端详情
        async function viewClientDetails(machineId) {
            try {
                // 获取客户端详情
                const response = await fetch(`${SERVER_URL}/api/client/${machineId}`);
                const data = await response.json();
                
                if (!data.success) {
                    alert('获取客户端详情失败: ' + data.error);
                    return;
                }
                
                const client = data.data;
                
                // 创建模态框
                const modal = document.createElement('div');
                modal.style.position = 'fixed';
                modal.style.top = '0';
                modal.style.left = '0';
                modal.style.width = '100%';
                modal.style.height = '100%';
                modal.style.background = 'rgba(0,0,0,0.7)';
                modal.style.display = 'flex';
                modal.style.justifyContent = 'center';
                modal.style.alignItems = 'center';
                modal.style.zIndex = '1000';
                
                // 格式化日期
                const formatDate = (dateString) => {
                    if (!dateString) return '未知';
                    try {
                        return new Date(dateString).toLocaleString();
                    } catch (e) {
                        return dateString;
                    }
                };
                
                // 处理系统信息
                let systemInfoHTML = '<p>无系统信息</p>';
                if (client.systemInfo) {
                    const info = client.systemInfo;
                    systemInfoHTML = `
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">操作系统</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${info.platform || '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">系统版本</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${info.release || '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">处理器</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${info.cpuModel || '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">内存</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${info.totalMemory ? Math.round(info.totalMemory / 1024 / 1024 / 1024) + ' GB' : '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">主机名</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${info.hostname || '未知'}</td>
                            </tr>
                        </table>
                    `;
                }
                
                // 处理授权信息
                let licenseInfoHTML = '<p>无授权信息</p>';
                if (client.licenseInfo) {
                    const license = client.licenseInfo;
                    licenseInfoHTML = `
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">授权ID</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.id || '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">类型</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.type || '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">过期时间</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${formatDate(license.expiryDate)}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">剩余时间</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.remainingTime?.formatted || '未知'}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">功能权限</td>
                                <td style="padding: 8px; border-bottom: 1px solid #eee;">${license.features ? license.features.join(', ') : '基础功能'}</td>
                            </tr>
                        </table>
                    `;
                }
                
                // 模态框内容
                const modalContent = document.createElement('div');
                modalContent.style.background = 'white';
                modalContent.style.borderRadius = '10px';
                modalContent.style.padding = '30px';
                modalContent.style.width = '90%';
                modalContent.style.maxWidth = '900px';
                modalContent.style.maxHeight = '90vh';
                modalContent.style.overflowY = 'auto';
                modalContent.style.position = 'relative';
                
                const isOnline = client.status === 'online';
                
                modalContent.innerHTML = `
                    <div style="position: absolute; top: 15px; right: 15px;">
                        <button id="closeModal" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <h2 style="margin-bottom: 10px;">客户端详情</h2>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span class="online-indicator ${isOnline ? 'online' : 'offline'}" style="width: 12px; height: 12px;"></span>
                            <span style="font-size: 16px; font-weight: 600;">${isOnline ? '在线' : '离线'}</span>
                        </div>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div>
                            <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                                <h3 style="margin-bottom: 15px;">基本信息</h3>
                                <table style="width: 100%; border-collapse: collapse;">
                                    <tr>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">机器ID</td>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee;">${client.machineId}</td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">状态</td>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee;">${client.status}</td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">首次连接</td>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee;">${formatDate(client.firstSeen)}</td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold;">最后活跃</td>
                                        <td style="padding: 8px; border-bottom: 1px solid #eee;">${formatDate(client.lastSeen)}</td>
                                    </tr>
                                </table>
                            </div>
                            
                            <div style="background: #f8f9fa; padding: 15px; border-radius: 8px;">
                                <h3 style="margin-bottom: 15px;">系统信息</h3>
                                ${systemInfoHTML}
                            </div>
                        </div>
                        
                        <div>
                            <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                                <h3 style="margin-bottom: 15px;">授权信息</h3>
                                ${licenseInfoHTML}
                            </div>
                            
                            <div style="background: #f8f9fa; padding: 15px; border-radius: 8px;">
                                <h3 style="margin-bottom: 15px;">远程操作</h3>
                                <p style="margin-bottom: 15px;">对此客户端执行操作:</p>
                                <div style="display: flex; gap: 10px;">
                                    <button onclick="remoteRevoke('${client.machineId}')" class="btn-danger" style="flex: 1;">
                                        撤销授权
                                    </button>
                                    <button onclick="refreshClient('${client.machineId}')" style="flex: 1;">
                                        刷新信息
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                modal.appendChild(modalContent);
                document.body.appendChild(modal);
                
                // 关闭模态框
                document.getElementById('closeModal').addEventListener('click', () => {
                    document.body.removeChild(modal);
                });
                
                // 点击模态框外部关闭
                modal.addEventListener('click', (event) => {
                    if (event.target === modal) {
                        document.body.removeChild(modal);
                    }
                });
                
                // 远程撤销授权
                window.remoteRevoke = async (machineId) => {
                    document.body.removeChild(modal);
                    document.getElementById('remoteMachineId').value = machineId;
                    document.getElementById('revokeReason').focus();
                    window.scrollTo(0, document.getElementById('remoteMachineId').offsetTop - 100);
                };
                
                // 刷新客户端信息
                window.refreshClient = async (machineId) => {
                    document.body.removeChild(modal);
                    loadClients();
                    setTimeout(() => {
                        viewClientDetails(machineId);
                    }, 500);
                };
                
            } catch (error) {
                console.error('获取客户端详情失败:', error);
                alert('获取客户端详情失败: ' + error.message);
            }
        }
    </script>
</body>
</html>
